/*******************************************************************************
 * Copyright 2011 Towee.net
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package net.towee.client.widgets.upload.impl;

import net.towee.client.widgets.upload.fileapi.File;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.http.client.URL;

public class XHRUploadController {
	private final File file;
	private final XHRUploadHandler handler;
	private String response;
	private JavaScriptObject xhr = null;

	public XHRUploadController(File file, XHRUploadHandler handler) {
		this.file = file;
		this.handler = handler;
	}

	public String getResponse() {
		return response;
	}

	public void send() {
		doSendFile(file.asJsObject(), handler);
	}

	public native void abort() /*-{
		var xhr = this.@net.towee.client.widgets.upload.impl.XHRUploadController::xhr;

		if (xhr != null)
			xhr.abort();
	}-*/;

	private native void doSendFile(JavaScriptObject file, XHRUploadHandler handler) /*-{
		var xhr = new XMLHttpRequest(), upload = xhr.upload, that = this;
		xhr.open("POST", "/attachment");

		// For aborting purpose
		this.@net.towee.client.widgets.upload.impl.XHRUploadController::xhr = xhr;

		// If supported FileReaader and given file is image
		if ($wnd.FileReader != null && file.type.match("image.*") && file.size < 512000) {
			var reader = new FileReader();

			reader.onload = function(e) {
				handler.@net.towee.client.widgets.upload.impl.XHRUploadHandler::onDataURLReed(Ljava/lang/String;)(e.target.result);
			};

			reader.readAsDataURL(file);
		}

		upload.onprogress = function(evt) {
    		if (evt.lengthComputable) {
        		handler.@net.towee.client.widgets.upload.impl.XHRUploadHandler::onProgress(II)(evt.loaded, evt.total);
    		}
		};

		upload.onloadstart = function(ev) {
		}

		upload.onload = function(ev) {
		};

		upload.onerror = function(ev) {
			handler.@net.towee.client.widgets.upload.impl.XHRUploadHandler::onError()();
		};

		upload.onabort = function(ev) {
			handler.@net.towee.client.widgets.upload.impl.XHRUploadHandler::onAbort()();
		};

		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					that.@net.towee.client.widgets.upload.impl.XHRUploadController::response = xhr.responseText;
					handler.@net.towee.client.widgets.upload.impl.XHRUploadHandler::onLoaded(Ljava/lang/String;)(xhr.responseText);
				}
			}
		};

		// Send data
		if ($wnd.FormData != null) {
			// W3C (Chrome, Safari, Firefox 4+)                
			var formData = new FormData();
			formData.append('file', file);
			xhr.send(formData);
		} else if ($wnd.FileReader != null && xhr.sendAsBinary) {
			// firefox < 4                 
			var boundary = "---------------------------550066842149661668836392148"                
			xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary=" + boundary);
			xhr.setRequestHeader("Cache-Control", "no-cache");
			var filename = unescape(encodeURIComponent( file.name ));
			var body = "--" + boundary + "\r\n";
			body += "Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n";
			body += "Content-Type: "+ file.type +"\r\n\r\n";
			body += (file.getAsBinary ? file.getAsBinary()
					: file.readAsBinary())
					+ "\r\n";
			body += "--" + boundary + "--\r\n";
			xhr.sendAsBinary(body);
		}
	}-*/;
	
	/**
	 * 
	http://localhost:8080/attachment

POST /attachment HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.9.2.20) Gecko/20110803 Firefox/3.6.20
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Content-Type: multipart/form-data, boundary=g8765vjdfd5u7k
Cache-Control: no-cache, no-cache
Referer: http://localhost:8080/ui/hosted.html?ui
Content-Length: 53909
Cookie: JSESSIONID=ckdry28eanq8c4kayswb5ugx
Pragma: no-cache
--g8765vjdfd5u7k
Content-Disposition: form-data; name='file'; filename='ann.jpe'
Content-Type: application/octet-stream

ÿØÿà
HTTP/1.1 200 OK
Content-Length: 0
Server: Jetty(7.4.5.v20110725)



http://localhost:8080/attachment

POST /attachment HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:5.0) Gecko/20100101 Firefox/5.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/*;q=0.8
Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Referer: http://localhost:8080/ui/hosted.html?ui
Content-Length: 53977
Content-Type: multipart/form-data; boundary=---------------------------550066842149661668836392148
Cookie: JSESSIONID=51xw050olq4x1k2r8btom1vg9
Pragma: no-cache
Cache-Control: no-cache
-----------------------------550066842149661668836392148
Content-Disposition: form-data; name="file"; filename="ann.jpe"
Content-Type: image/jpeg

ÿØÿà
HTTP/1.1 200 OK
Content-Type: text/plain;charset=UTF-8
Content-Length: 34
Server: Jetty(7.4.5.v20110725)

	 * @param t
	 * @return
	 */

	public String test(String t) {
		return URL.encode(t);
	}
}
